from app.database.connector import Database


# noinspection SqlNoDataSourceInspection
class BaseDAO:
    """通用 DAO 基类"""
    def __init__(self, table_name, db=None):
        self.table_name = table_name
        self.db = db or Database()  # 允许传入数据库连接实例

    def find_by_id(self, record_id):
        """根据 ID 查询单条记录"""
        query = f"SELECT * FROM {self.table_name} WHERE id = %s"
        result = self.db.execute_query(query, (record_id,))
        return result[0] if result else None

    def find_all(self, limit=10, offset=0, conditions=None):
        """查询所有记录
        Args:
            limit: 每页记录数
            offset: 偏移量
            conditions: 查询条件字典，格式为 {字段名: 值}
        """
        query = f"SELECT * FROM {self.table_name}"
        params = []

        if conditions:
            where_clauses = []
            for key, value in conditions.items():
                where_clauses.append(f"{key} = %s")
                params.append(value)
            if where_clauses:
                query += " WHERE " + " AND ".join(where_clauses)

        query += " LIMIT %s OFFSET %s"
        params.extend([limit, offset])
        return self.db.execute_query(query, tuple(params))

    def create(self, data):
        """插入一条记录"""
        columns = ', '.join(data.keys())
        placeholders = ', '.join(['%s'] * len(data))
        query = f"INSERT INTO {self.table_name} ({columns}) VALUES ({placeholders})"
        return self.db.execute_update(query, tuple(data.values()))

    def update(self, record_id, data):
        """更新一条记录"""
        set_values = ', '.join([f"{key} = %s" for key in data.keys()])
        query = f"UPDATE {self.table_name} SET {set_values} WHERE id = %s"
        params = tuple(data.values()) + (record_id,)
        return self.db.execute_update(query, params)

    def delete(self, record_id):
        """删除一条记录"""
        query = f"DELETE FROM {self.table_name} WHERE id = %s"
        return self.db.execute_update(query, (record_id,))